package org.example.warehouse.service.impl;

import java.util.Date;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import org.example.contract.domain.ContractProduct;
import org.example.contract.mapper.ContractProductMapper;
import org.example.utils.Util;
import org.example.warehouse.domain.WarehouseStore;
import org.example.warehouse.mapper.OrderDetailMapper;
import org.example.warehouse.mapper.WarehouseStoreMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.warehouse.mapper.SellStoreDetailMapper;
import org.example.warehouse.domain.SellStoreDetail;
import org.example.warehouse.service.ISellStoreDetailService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 仓库出库详情Service业务层处理
 *
 * @author 小孟微信：xiaomengcode
 * @date 2024-04-12
 */
@Service
public class SellStoreDetailServiceImpl implements ISellStoreDetailService
{
    @Autowired
    private SellStoreDetailMapper sellStoreDetailMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WarehouseStoreMapper warehouseStoreMapper;

    @Autowired
    private ContractProductMapper contractProductMapper;

    /**
     * 查询仓库出库详情
     *
     * @param sellDetailId 仓库出库详情主键
     * @return 仓库出库详情
     */
    @Override
    public SellStoreDetail selectSellStoreDetailBySellDetailId(Long sellDetailId)
    {
        return sellStoreDetailMapper.selectSellStoreDetailBySellDetailId(sellDetailId);
    }

    /**
     * 查询仓库出库详情列表
     *
     * @param sellStoreDetail 仓库出库详情
     * @return 仓库出库详情
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SellStoreDetail> selectSellStoreDetailList(SellStoreDetail sellStoreDetail)
    {
        Util.setQuerySelfData((BaseEntity) sellStoreDetail);
        return sellStoreDetailMapper.selectSellStoreDetailList(sellStoreDetail);
    }

    /**
     * 新增仓库出库详情
     *
     * @param sellStoreDetail 仓库出库详情
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSellStoreDetail(SellStoreDetail sellStoreDetail)
    {
        sellStoreDetail.setCreateBy(ShiroUtils.getUserId()+"");
        sellStoreDetail.setCreateTime(DateUtils.getNowDate());
        long total =Long.parseLong(sellStoreDetail.getParams().get ("code").toString());
        if(sellStoreDetail.getParams().containsKey("list")){
            String  list = sellStoreDetail.getParams().get("list").toString();
            List<ContractProduct> contractProducts = JSONUtil.parseArray(list).toList(ContractProduct.class);
            Date curDate=DateUtils.getNowDate();
            for(ContractProduct contractProduct:contractProducts){
                //1、更新合同产品清单
                contractProduct.setUseNum(contractProduct.getOperationNum()+handNullValue(contractProduct.getUseNum()));
                contractProduct.setRemainNum(handNullValue(contractProduct.getRemainNum())-contractProduct.getOperationNum());
                contractProduct.setCreateBy(ShiroUtils.getUserId()+"");
                contractProductMapper.updateContractProduct(contractProduct);

                WarehouseStore houseStoreDB = getWarehouseStore(contractProduct);
                //2、库存
                editWarehouseStore(contractProduct,houseStoreDB);

                //3、增加出库详情记录
                String storeDetailNo =  "GI"+DateUtils.dateTimeNow("yyMMdd")+String.format("%04d", ++total);
                insertSellStoreDetail(sellStoreDetail, contractProduct, storeDetailNo, houseStoreDB, curDate);
            }
            return contractProducts.size();

        }else{
            WarehouseStore houseStoreDB = getWarehouseStore(sellStoreDetail);
            String storeDetailNo =  "GI"+DateUtils.dateTimeNow("yyMMdd")+String.format("%04d", ++total);
            sellStoreDetail.setSellDetailNo(storeDetailNo);
            sellStoreDetail.setAverageMoney(houseStoreDB.getAverageMoney());
            sellStoreDetail.setOperationNum(sellStoreDetail.getNum());
            editWarehouseStore(sellStoreDetail,houseStoreDB);
            return sellStoreDetailMapper.insertSellStoreDetail(sellStoreDetail);
        }
    }

    private void insertSellStoreDetail(SellStoreDetail sellStoreDetail, ContractProduct contractProduct,  String storeDetailNo , WarehouseStore houseStoreDB, Date curDate) {

        SellStoreDetail storeDetail =new SellStoreDetail();

        storeDetail.setSellDetailNo(storeDetailNo);
        storeDetail.setOrderDetailId(contractProduct.getContractProductId());
        storeDetail.setContractId(sellStoreDetail.getContractId()+"");
        storeDetail.setWarehouseId(1L);
        storeDetail.setProductId(contractProduct.getProductId());
        storeDetail.setNum(contractProduct.getOperationNum());
        storeDetail.setPrice(contractProduct.getPrice());
        storeDetail.setAverageMoney(houseStoreDB.getAverageMoney());
        storeDetail.setCreateBy(ShiroUtils.getUserId()+"");
        storeDetail.setCreateTime(curDate);
        storeDetail.setRemark(contractProduct.getRemark());
        storeDetail.setSupplierId(contractProduct.getSupplierId());
        sellStoreDetailMapper.insertSellStoreDetail(storeDetail);
    }

    private void editWarehouseStore(ContractProduct contractProduct, WarehouseStore houseStoreDB) {
        if(houseStoreDB ==null || houseStoreDB.getWarehouseStoreId()<=0){
            throw new RuntimeException("库存没有该产品存在");
        }else{
            //更新库存
            houseStoreDB.setUseNum(handNullValue(houseStoreDB.getUseNum())+ contractProduct.getOperationNum());
            if(houseStoreDB.getRemainNum()- contractProduct.getOperationNum()<0){
                throw new RuntimeException(houseStoreDB.getName()+"：库存不足，【库存数量："+ houseStoreDB.getRemainNum()+"】 【出库数量："+contractProduct.getOperationNum()+"】");
            }
            houseStoreDB.setRemainNum(handNullValue(houseStoreDB.getRemainNum())- contractProduct.getOperationNum());
            warehouseStoreMapper.updateWarehouseStore(houseStoreDB);
        }
    }

    private WarehouseStore getWarehouseStore(ContractProduct contractProduct) {
        WarehouseStore store=new WarehouseStore();
        store.setProductId(contractProduct.getProductId());
        store.setWarehouseId(1L);
        store.getParams().put("deptId",ShiroUtils.getSysUser().getDeptId());
        WarehouseStore houseStoreDB= warehouseStoreMapper.selectMallWarehouseStoreByProductId(store);
        return houseStoreDB;
    }



    private Integer handNullValue(Integer value){

        if(value==null){
            return 0;
        }
        return value;
    }
    /**
     * 修改仓库出库详情
     *
     * @param sellStoreDetail 仓库出库详情
     * @return 结果
     */
    @Override
    public int updateSellStoreDetail(SellStoreDetail sellStoreDetail)
    {
        return sellStoreDetailMapper.updateSellStoreDetail(sellStoreDetail);
    }

    /**
     * 批量删除仓库出库详情
     *
     * @param sellDetailIds 需要删除的仓库出库详情主键
     * @return 结果
     */
    @Override
    public int deleteSellStoreDetailBySellDetailIds(String sellDetailIds)
    {
        return sellStoreDetailMapper.deleteSellStoreDetailBySellDetailIds(Convert.toStrArray(sellDetailIds));
    }

    /**
     * 删除仓库出库详情信息
     *
     * @param sellDetailId 仓库出库详情主键
     * @return 结果
     */
    @Override
    public int deleteSellStoreDetailBySellDetailId(Long sellDetailId)
    {
        return sellStoreDetailMapper.deleteSellStoreDetailBySellDetailId(sellDetailId);
    }
}
